package cn.itcast.nems.studentrecord.service.impl;

import cn.hutool.core.lang.Assert;
import cn.itcast.ic.common.exception.v2.BizExceptionProducer;
import cn.itcast.nems.common.enumeration.NemsErrorBodyEnum;
import cn.itcast.nems.manager.eca.ECAManager;
import cn.itcast.nems.manager.util.CustomBeanUtil;
import cn.itcast.nems.oldems.api.StudentApi;
import cn.itcast.nems.oldems.dto.ContractInfoDTO;
import cn.itcast.nems.studentrecord.constant.ContractStateEnum;
import cn.itcast.nems.studentrecord.constant.ContractTypeEnum;
import cn.itcast.nems.studentrecord.dao.dataobject.StudentRecordDO;
import cn.itcast.nems.studentrecord.dao.entity.StudentRecord;
import cn.itcast.nems.studentrecord.dao.entity.StudentRecordStudentRelationship;
import cn.itcast.nems.studentrecord.dto.StudentRecordDTO;
import cn.itcast.nems.studentrecord.dto.contract.StudentContractClazzDTO;
import cn.itcast.nems.studentrecord.dto.contract.StudentContractInfoDTO;
import cn.itcast.nems.studentrecord.enumeration.StudentRecordErrorBodyEnum;
import cn.itcast.nems.studentrecord.service.studentrecord.StudentRecordContractService;
import cn.itcast.nems.studentrecord.service.studentrecord.StudentRecordService;
import cn.itcast.nems.studentrecord.service.studentrecord.StudentRecordStudentRelationshipService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class StudentRecordContractServiceImpl implements StudentRecordContractService {
    private final StudentRecordService studentRecordService ;
    private final StudentRecordStudentRelationshipService studentRecordStudentRelationshipService ;
    private final StudentApi  studentApi ;
    private final ECAManager ecaManager ;

    @Override
    public List<StudentContractClazzDTO> findStudentClazzByStudentId(Integer studentId) {
        List<StudentRecordDO> recordInfoList  =studentRecordService.findValidStudentRecordByStudentId(studentId) ;
        if(CollectionUtils.isEmpty(recordInfoList)) {
            return  null ;
        }
        List<ContractInfoDTO> contractInfoList = Objects.requireNonNullElse(studentApi.findClassContractInfoByStudentId(studentId) , new ArrayList<>());
        Map<Integer,ContractInfoDTO> map   =contractInfoList.stream().collect(Collectors.toMap(ContractInfoDTO::getClazzId , p-> p)) ;
        return recordInfoList.stream().map(item -> {
            StudentContractClazzDTO contractClazzDTO = CustomBeanUtil.copyProperties(item ,new StudentContractClazzDTO()) ;
            contractClazzDTO.setStudentRecordId(item.getId());
            ContractInfoDTO contractInfoDTO = map.get(item.getClazzId())  ;
            contractClazzDTO.setContractState(ContractStateEnum.convertContractStateEnum(Objects.nonNull(contractInfoDTO)?contractInfoDTO.getContractState(): null));
            return contractClazzDTO ;
        }).toList();
    }

    @Override
    public List<StudentContractInfoDTO> findStudentClazzByStudentRecordId(String studentRecordId, String contractNumber) {
        StudentContractClazzDTO studentContractClazzDTO =new StudentContractClazzDTO() ;
        StudentRecord studentRecord  =  studentRecordService.getById(studentRecordId) ;
        Assert.notNull(studentRecord , BizExceptionProducer.produce(NemsErrorBodyEnum.DATA_EXIST ,"学籍ID："+ studentRecordId));
        studentContractClazzDTO.setClazzId(studentRecord.getClazzId());
        List<StudentRecordStudentRelationship>  relationships = studentRecordStudentRelationshipService.findByStudentRecordId(studentRecordId);
        List<ContractInfoDTO> contractInfoList = studentApi.findContractClazzByStudentIdAndClazzId(relationships.get(0).getStudentId() , studentRecord.getClazzId(), contractNumber)  ;
        List<StudentContractInfoDTO> contractList =new ArrayList<>() ;
        if(CollectionUtils.isEmpty(contractInfoList)) {
            return Collections.emptyList() ;
        }
        for (ContractInfoDTO contractInfoDTO : contractInfoList) {
            StudentContractInfoDTO studentContractInfoDTO =  CustomBeanUtil.copyProperties(contractInfoDTO ,new StudentContractInfoDTO()) ;
            studentContractInfoDTO.setContractState(ContractStateEnum.convertContractStateEnum(contractInfoDTO.getContractState()));
            studentContractInfoDTO.setContractType(ContractTypeEnum.getByName(contractInfoDTO.getContractType()));
            contractList.add(studentContractInfoDTO) ;
        }

        return contractList;
    }

    @Override
    public String getContractUrl(String studentRecordId, String contractNumber) {
        try {
            List<StudentContractInfoDTO>  contractInfoList= this.findStudentClazzByStudentRecordId(studentRecordId , contractNumber) ;
            log.info("【获取合同链接】学籍ID：{}，合同编号：{}，查询结果：{}" ,studentRecordId ,contractNumber , JSON.toJSONString(contractInfoList , SerializerFeature.DisableCircularReferenceDetect));
            Assert.notEmpty(contractInfoList , BizExceptionProducer.produce(NemsErrorBodyEnum.DATA_EXIST ,String.format("学籍ID【%s】，合同编号【%s】",studentRecordId ,contractNumber)));
            ContractStateEnum stateEnum = contractInfoList.get(0).getContractState() ;
            return ecaManager.getContractUrl(contractInfoList.get(0).getContractNumber(), ecaManager.convertContractStatus(Objects.nonNull(stateEnum) ? stateEnum.name() : null));
        } catch (Exception e) {
            log.info("【获取合同链接】调用ECA接口失败，详情：{}", e.getMessage());
            BizExceptionProducer.throwProduce(e, StudentRecordErrorBodyEnum.CONTRACT_NOT_FUND);
            return null;
        }
    }
}
